package com.hualude.roadsign.utils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Random;

/**
 * 验证码生成器
 */
public class Captcha {
    // 设置图片宽度。
    private int width = 120;
    // 设置图片高度。
    private int height = 50;
    // 设置验证码字符个数
    private int codeNum = 4;
    // 设置验证码干扰线数
    private int lineNum = 20;
    // 设置验证码字符串
    private String code = null;
    // 设置验证码图片缓存
    private BufferedImage buffImg = null;

    private char[] codeQue = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
            'I', 'J', 'K', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
            'X', 'Y', 'Z', '2', '3', '4', '5', '6', '7', '8', '9'};

    // 生成随机数
    private Random random = new Random();

    // 无参构造方法
    public Captcha() {
        this.createCode();
    }

    /**
     * 有图片宽高的构造方法
     */
    public Captcha(int width, int height) {
        this.width = width;
        this.height = height;
        this.createCode();
    }

    /**
     * 有图片宽高、字符个数、干扰线条数构造方法
     */
    public Captcha(int width, int height, int codeNum, int lineNum) {
        this.width = width;
        this.height = height;
        this.codeNum = codeNum;
        this.lineNum = lineNum;
        this.createCode();
    }


    public void createCode() {
        int codeX;
        int fontHeight;
        fontHeight = height - 10;// 字体的高度
        codeX = width / (codeNum + 3);// 每个字符的宽度

        // 图像 buffer
        buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = buffImg.createGraphics();

        // 图像背景填充为白色
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, width, height);

        // 创建字体
        ImgFontByte imgFont = new ImgFontByte();
        Font font = imgFont.getFont(fontHeight);
        g.setFont(font);

        // 绘制干扰线，对此处的参数公式进行修改，将会得到不同的验证码样式
        for (int i = 0; i < lineNum; i++) {
            int xP = getRandomNumber(width / 2);
            int yP = getRandomNumber(height * 5);
            int xD = xP + getRandomNumber(width * 5);
            int yD = getRandomNumber(height / 2);
            g.setColor(getRandomColor());
            g.drawLine(xP, yP, xD, yD);
        }

        StringBuffer randomCode = new StringBuffer();
        // 在字符队列中，产生随机的验证码字符
        for (int i = 0; i < codeNum; i++) {
            String strRand = String.valueOf(codeQue[random.nextInt(codeQue.length)]);
            // 设置字体颜色为随机获取
            g.setColor(getRandomColor());
            // 设置字体位置尽量在图片中间，并且有聚集
            g.drawString(strRand, (i + 1) * codeX,
                    getRandomNumber(height / 2) + 30);
            randomCode.append(strRand);
        }
        code = randomCode.toString();
    }

    /*
    * 获取随机颜色
    */
    private Color getRandomColor() {
        int r = getRandomNumber(255);
        int g = getRandomNumber(255);
        int b = getRandomNumber(255);
        return new Color(r, g, b);
    }

    /*
    * 获取随机数
    */
    private int getRandomNumber(int number) {
        return random.nextInt(number);
    }

    public void write(String path) throws IOException {
        OutputStream sos = new FileOutputStream(path);
        this.write(sos);
    }

    public void write(OutputStream sos) throws IOException {
        ImageIO.write(buffImg, "png", sos);
        sos.close();
    }

    public BufferedImage getBuffImg() {
        return buffImg;
    }

    public String getCode() {
        return code;
    }

    /*
    * 字体样式类
    */
    class ImgFontByte {
        public Font getFont(int fontHeight) {
            try {
                Font baseFont = Font.createFont(Font.TRUETYPE_FONT,
                        new ByteArrayInputStream(hex2byte(getFontByteStr())));
                return baseFont.deriveFont(Font.PLAIN, fontHeight);
            } catch (Exception e) {
                return new Font("Arial", Font.PLAIN, fontHeight);
            }
        }

        private byte[] hex2byte(String str) {
            if (str == null)
                return null;
            str = str.trim();
            int len = str.length();
            if (len == 0 || len % 2 == 1)
                return null;

            byte[] b = new byte[len / 2];
            try {
                for (int i = 0; i < str.length(); i += 2) {
                    b[i / 2] = (byte) Integer.decode(
                            "0x" + str.substring(i, i + 2)).intValue();
                }
                return b;
            } catch (Exception e) {
                return null;
            }
        }

        // 字体文件的十六进制字符串,使用文件流读入之前获取到的 HexString.txt 文件的内容。
        private String getFontByteStr() {
            String pathName = "/resources/HexString.txt";
            String tempStr = null;
            BufferedReader reader;
            try {
                reader = new BufferedReader(new InputStreamReader(Captcha.class.getResourceAsStream(pathName)));
                tempStr = reader.readLine();
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return tempStr;
        }
    }
}
